<?php
/**
 * @author Mingming Tang iamalazyrat@gmail.com
 */

class Collection_Controller extends Base_Controller {

  public $restful = true;

  public function get_index() {
    return Redirect::to(URL::to('collection/list'));
  }

  public function get_edit() {
    $id = Input::get('id', false);
    if (!$id) return View::make('collection.edit.not_found');
    $collection = Collection::find($id);
    if (!$collection) return View::make('collection.edit.not_found');
    return View::make('collection.edit.main')->with('collection', $collection);
  }


  public function post_edit() {
    $input = Input::all();
    $rules = array(
      'name'  => 'required|max:64|unique:collections,name,'.$input['id'],
      'description' => 'required|max:256',
    );
    $messages = array(
      'name_required' => '忘记写专题名称了喔...',
      'name_unique' => '这个专题名称已经有了喔...',
      'name_max' => '专题名称太长了喔...',
      'description_required' => '写点专题描述吧...',
      'description_max' => '专题描述太长了喔...',
    );
    $validation = Validator::make($input, $rules, $messages);
    if ($validation->fails()) {
      return View::make('collection.edit.fail')->with('error', $validation->errors);
    } else {
      $c = Collection::find($input['id']);
      $c->name = Input::get('name', '');
      $c->description = Input::get('description', '');
      $c->save();
      return View::make('collection.edit.succ');
    }
  }
  

  public function get_pick_taobao() {
    $id = Input::get('id', false);
    $collection = Collection::with('products')->find($id);
    if (!$collection) return View::make('collection.pick_taobao.not_found');
    $categories = Category::all();
    $products = array();
    $keyword = Input::get('keyword', false);
    $cid = Input::get('cid', false);
    $sort= Input::get('sort', false);
    $page = Input::get('p', 1);
    if ($cid OR $keyword) {
      $field = array('num_iid', 'seller_id', 'nick', 'title', 'price', 'item_location', 'seller_credit_score', 'click_url', 'shop_click_url', 'pic_url', 'taobaoke_cat_click_url', 'keyword_click_url', 'coupon_rate', 'coupon_price', 'coupon_start_time', 'coupon_end_time', 'commission_rate', 'commission', 'commission_num', 'commission_volume', 'volume', 'shop_type');
      $c = new TopClient;
      $c->appkey = Config::get('option.appkey', '');
      $c->secretKey = Config::get('option.secret', '');
      $req = new TaobaokeItemsGetRequest;
      $req->setFields(implode(',', $field));
      $req->setCid($cid);
      $req->setSort($sort);
      $req->setKeyword($keyword);
      $req->setPageNo($page);
      $resp = $c->execute($req);
      $products = $resp->taobaoke_items;
    } 
    $url = url('collection/pick_taobao') . "?id={$collection->id}&cid={$cid}&sort={$sort}&keyword={$keyword}";
    $page = Pagination::page($page, 400, 40, $url);
    return View::make('collection.pick_taobao.main')->with('collection', $collection)->with('categories', $categories)->with('products', $products)->with('cid', $cid)->with('page', $page)->with('keyword', $keyword)->with('sort', $sort);
  }

  public function post_save_keyword() {
    $data = Input::get();
    if (!isset($data['collection_id']) OR !isset($data['keyword']) OR trim($data['keyword']) == '') return Response::json(array('code'=>400));
    $keyword = trim($data['keyword']);
    if (!Keyword::where('keyword', '=', $keyword)->where('collection_id', '=', $data['collection_id'])->where('cid', '=', $data['cid'])->first()){
      Keyword::create(array('keyword' => $keyword, 'collection_id' => $data['collection_id'], 'cid' => $data['cid']));
    }
    return Response::json(array('code'=>200));
  }

  public function post_delete_keyword() {
    $data = Input::get();
    if (!isset($data['collection_id']) OR !isset($data['keyword']) OR trim($data['keyword']) == '') return Response::json(array('code'=>400));
    $keyword = trim($data['keyword']);
    if (!Keyword::where('keyword', '=', $keyword)->where('collection_id', '=', $data['collection_id'])->where('cid', '=', $data['cid'])->first()){
      return Response::json(array('code'=>200));
    } else {
      Keyword::where('keyword', '=', $keyword)->where('collection_id', '=', $data['collection_id'])->where('cid', '=', $data['cid'])->delete();
    }
    return Response::json(array('code'=>200));
  }

  public function post_unpick() {
    $product_id = Input::get('product_id', false);
    $collection_id = Input::get('collection_id', false);
    if (!$product_id OR !$collection_id) return Response::json(array('code', '400'));
    $collection = Collection::find($collection_id);
    if (!$collection) return Response::json(array('code'=>400));
    DB::table('collection_product')->where('product_id', '=', $product_id)->where('collection_id', '=', $collection_id)->delete();
    if (!DB::table('collection_product')->where('product_id', '=', $product_id)->first()) {
      Product::find($product_id)->delete();
      Img::where('product_id', '=', $product_id)->delete();
    }
    $collection->amount -= 1;
    $collection->save();
    return Response::json(array('code'=>'200'));
  }

  public function post_pick_taobao_save() {
    $item = Input::get('item', false);
    $img= Input::get('img', array());
    $collection_id = Input::get('collection_id', false);
    if (!$item or !$collection_id) return Response::json(array('code', 400));
    $product = Product::where('num_iid', '=', $item['num_iid'])->first();
    $collection = Collection::find($collection_id);
    if (!$collection) return Response::json(array('code'=>400));
    if (!$product) {
      $product = Product::create($item);
    }
    if ($product) {
      if (!DB::table('collection_product')->where('collection_id', '=', $collection_id)->where('product_id', '=', $product->id)->first()) {
        DB::table('collection_product')->insert(array('collection_id'=>$collection_id, 'product_id'=>$product->id));
        $collection->amount += 1;
        $collection->save();
      }
      Img::where('product_id', '=', $product->id)->delete();
      foreach ($img as $v) {
        if (!Img::where('url', '=', $v)->first()) {
          Img::create(array('url' => $v, 'product_id'=>$product->id, 'collection_id'=>$collection_id));
        }
      }
      if (!$img) {
        if (!Img::where('url', '=', $product->pic_url)->first()) {
          Img::create(array('url' => $product->pic_url, 'product_id'=>$product->id, 'collection_id'=>$collection_id));
        }
      }
      return Response::json(array('code'=>200));
    }
    return Response::json(array('code', 400));
  }

  public function get_item_info() {
    $num_iid = Input::get('num_iid', false);
    if (!$num_iid) return Response::json(array('code'=>400));
    $c = new TopClient;
    $c->appkey = Config::get('option.appkey', '');
    $c->secretKey = Config::get('option.secret', '');
    $req = new ItemGetRequest;
    $req->setFields("prop_img.url,item_img.url,nick");
    $req->setNumIid($num_iid);
    $resp = $c->execute($req);
    $imgs = array();
    if (isset($resp->item->prop_imgs->prop_img)) {
      foreach ($resp->item->prop_imgs->prop_img as $i) {
        $selected = 'n';
        if (Img::where('url', '=', strval($i->url))->first()) $selected = 'y';
        $imgs[] = array('url' => strval($i->url), 'selected' => $selected);
      }
    }
    $product = Product::where('num_iid', '=', $num_iid)->first();
    if ($product) {
      $selected = 'n';
      if (Img::where('url', '=', strval($product->pic_url))->first()) $selected = 'y';
      $imgs[] = array('url' => $product->pic_url, 'selected' => $selected);
    }
    return Response::json(array('code'=>200, 'imgs'=>$imgs));
  }


  public function get_list() {
    $collections = Collection::all();
    $collections = array_reverse($collections);
    return View::make('collection.list.main')->with('collections', $collections);
  }

  public function get_info() {
    $id = Input::get('id', false);
    $sort = Input::get('sort', false);
    $page = Input::get('p', 1);
    $per_page = 40;
    if (!$sort) {
      $collection = Collection::with('products')->find($id);
    } else {
      $collection = Collection::find($id);
      if (!$collection) return View::make('collection.info.not_found');
      switch ($sort) {
        case 'price_desc':
          $products = Product::order_by('price', 'desc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'price_asc':
          $products = Product::order_by('price', 'asc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'commissionRate_desc':
          $products = Product::order_by('commission_rate', 'desc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'commissionRate_asc':
          $products = Product::order_by('commission_rate', 'asc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'commissionNum_desc':
          $products = Product::order_by('commission_num', 'desc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'commissionNum_asc':
          $products = Product::order_by('commission_num', 'asc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'commissionVolume_desc':
          $products = Product::order_by('commission_num', 'desc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        case 'commissionVolume_asc':
          $products = Product::order_by('commission_volume', 'asc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
        default:
          $products = Product::order_by('id', 'desc')->take($per_page)->skip(($page-1)*$per_page)->get();
          break;
      }
      $collection->products = $products;
    }
    if (!$collection) return View::make('collection.info.not_found');
    $url = url('collection/info') . "?id={$collection->id}&sort={$sort}";
    $cnt = DB::table('collection_product')->where('collection_id', '=', $collection->id)->count();
    $page = Pagination::page($page, $cnt, 40, $url);
    return View::make('collection.info.main')->with('collection', $collection)->with('sort', $sort)->with('page', $page);
  }

  public function post_op() {
    $op = Input::get('op', false); 
    $data = Input::get('data', false);
    if (!$op) return Response::json(array('code' => 400));
    if (!$data OR !isset($data['id'])) return Response::json(array('code' => 400));
    $collection = Collection::find($data['id']);
    if (!$collection) return Response::json(array('code' => 404));
    switch ($op) {
      case 'enable':
        $collection->status = 1;
        break;
      case 'disable':
        $collection->status = 0;
        break;
      case 'delete':
        $collection->delete();
        return Response::json(array('code' => 200));
        break;
      default:
        return Response::json(array('code' => 400));
        break;
    }
    if ($collection->save()) return Response::json(array('code'=>200));
  }

  public function get_add() {
    return View::make('collection.add.main');
  }

  public function post_add() {
    $input = Input::all();
    $rules = array(
      'name'  => 'required|max:64|unique:collections,name',
      'description' => 'required|max:256',
    );
    $messages = array(
      'name_required' => '忘记写专题名称了喔...',
      'name_unique' => '这个专题名称已经有了喔...',
      'name_max' => '专题名称太长了喔...',
      'description_required' => '写点专题描述吧...',
      'description_max' => '专题描述太长了喔...',
    );
    $validation = Validator::make($input, $rules, $messages);
    if ($validation->fails()) {
      return View::make('collection.add.fail')->with('error', $validation->errors);
    } else {
      $c = new Collection();
      $c->name = Input::get('name', '');
      $c->description = Input::get('description', '');
      $c->save();
      return View::make('collection.add.succ');
    }
  }


  public function post_sort_op() {
    $data = Input::all();
    if (!$data OR !isset($data['collection_id']) OR !isset($data['op'])) return Response::json(array('code'=>400));
    $collection = Collection::find($data['collection_id']);
    if (!$collection) return Response::json(array('code' => 400));
    switch ($data['op']) {
      case 'plus':
        $collection->sort += 1;
        $collection->save();
        return Response::json(array('code'=>200, 'sort'=>$collection->sort));
        break;
      case 'minus':
        $collection->sort -= 1;
        $collection->save();
        return Response::json(array('code'=>200, 'sort'=>$collection->sort));
        break;
      default:
        return Response::json(array('code'=>400));
        break;
    }
  }
}
